package com.cash.app.ui.login

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.widget.AppCompatButton
import com.cash.app.BuildConfig
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant.LOGIN_COUNT_DOWN
import com.cash.app.constant.AppConstant.LOGIN_COUNT_DOWN_INTERVAL
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcLoginBinding
import com.cash.app.manager.GlobalTaskManager
import com.cash.app.utils.hide
import com.cash.app.utils.visible

class LoginActivity : BaseActivity() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, LoginActivity::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var binding: AcLoginBinding

    private val viewModel: LoginViewModel by viewModels()

    private lateinit var phoneEditText: EditText
    private lateinit var codeEditText: EditText
    private lateinit var getCodeButton: TextView
    private lateinit var loginButton: AppCompatButton
    private var countDownTimer: CountDownTimer? = null

    private var isChannel = true

    override val statusBarTextDark: Boolean
        get() = false

    override val statusBarColor: Int
        get() = R.color.transparent

    override fun setViewBind() {
        binding = AcLoginBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun getAppActionBar(): AppActionBar? {
        return binding.actionBar
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        setupObservers()
        // check temp token
        GlobalTaskManager.getTempToken()
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        phoneEditText = binding.phoneEt
        codeEditText = binding.codeEt
        getCodeButton = binding.tvGetCode
        loginButton = binding.btnLogin

        // Get verification code button click
        binding.tvGetCode.setOnClickListener {
            val phone = binding.phoneEt.text.toString()
            if (phone.isEmpty()) {
                toast(R.string.login_tip_phone)
                return@setOnClickListener
            }
            if (phone.length != 10) {
                toast(R.string.login_tip_phone_2)
                return@setOnClickListener
            }
            viewModel.getCode(phone, if (isChannel) 0 else 1)
            isChannel = !isChannel
        }

        // Login button click
        binding.btnLogin.setOnClickListener {
            val phone = binding.phoneEt.text.toString()
            val code = binding.codeEt.text.toString()

            if (phone.isEmpty() || code.isEmpty()) {
                toast(R.string.login_tip_2)
                return@setOnClickListener
            }

            if (phone.length != 10) {
                toast(R.string.login_tip_phone_2)
                return@setOnClickListener
            }

            viewModel.login(phone, code)
        }
        if (BuildConfig.UPLOAD_CONFIG.isNotEmpty()) {
            // can't apply:1998121906 , have order:8230331004
            binding.phoneEt.setText("4123123456")
            binding.codeEt.setText("123456")
        }
    }

    private fun setupObservers() {
        viewModel.loginResult.observe(this) { loginResult ->
            if (loginResult) {
                setResult(RESULT_OK)
                finish()
                //toast(R.string.login_success)
            } else {
                //toast(R.string.login_failed)
            }
        }

        viewModel.getCodeResult.observe(this) { codeResult ->
            if (codeResult) {
                //toast(R.string.login_get_code_success)
                showCountdown()
            } else {
                //toast(R.string.login_get_code_failed)
            }
        }
    }

    private fun showCountdown() {
        binding.tvGetCode.hide()
        binding.tvCountdown.visible()
        countDownTimer = object : CountDownTimer(LOGIN_COUNT_DOWN, LOGIN_COUNT_DOWN_INTERVAL) {
            override fun onTick(millisUntilFinished: Long) {
                val seconds = millisUntilFinished / LOGIN_COUNT_DOWN_INTERVAL
                binding.tvCountdown.text =
                    getString(R.string.unit_second, seconds.toString())
            }

            override fun onFinish() {
                binding.tvCountdown.text = getString(R.string.unit_second, "0")
                binding.tvCountdown.hide()
                binding.tvGetCode.visible()
            }
        }.start()
    }

    private fun toast(strRes: Int) {
        Toast.makeText(this, getString(strRes), Toast.LENGTH_SHORT).show()
    }

    private fun toast(str: String) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
    }
}
